/**
 *  HEX color to RGB
 */
export function hexToRGB(hex: string) {
  let sHex = hex.toLowerCase();
  if (sHex.length === 4) {
    let sColorNew = '#';
    for (let i = 1; i < 4; i += 1) {
      sColorNew += sHex.slice(i, i + 1).concat(sHex.slice(i, i + 1));
    }
    sHex = sColorNew;
  }
  const sColorChange: number[] = [];
  for (let i = 1; i < 7; i += 2) {
    sColorChange.push(parseInt('0x' + sHex.slice(i, i + 2)));
  }
  return sColorChange;
}

/**
 * 颜色反转
 * @param hex
 * @returns
 */
export function invertColor(hex: string) {
  // 将十六进制颜色转换为RGB
  let [r, g, b] = hexToRGB(hex);

  r = 255 - r;
  g = 255 - g;
  b = 255 - b;

  // 2. 保证RGB在256色容器内
  r = r.toString(16).padStart(2, '0') as unknown as number;
  g = g.toString(16).padStart(2, '0') as unknown as number;
  b = b.toString(16).padStart(2, '0') as unknown as number;

  return `#${r}${g}${b}`;
}

/**
 * 判断颜色是否是深色
 * @param hexColor
 * @returns
 */
export function isDarkColor(hexColor: string) {
  // 将十六进制颜色转换为RGB
  const [r, g, b] = hexToRGB(hexColor);

  // 计算亮度
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;

  // 根据亮度判断颜色类型
  return brightness < 128;
}
